package org.budo.redis.jdbc.driver.statement.script;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.budo.jdbc.driver.resultset.impl.ObjectArrayResultSet;
import org.budo.redis.jdbc.driver.BudoRedisJdbcConnection;
import org.budo.redis.jdbc.driver.BudoRedisJdbcPreparedStatement;
import org.budo.redis.jdbc.driver.executor.RedisStatementExecutor;
import org.budo.redis.jdbc.driver.statement.AbstractRedisStatement;

/**
 * @author lmw
 */
public class EVAL extends AbstractRedisStatement {
    @Override
    public void execute(PreparedStatement preparedStatement) throws SQLException {
        byte[] script = this.parameter(0, preparedStatement);

        RedisStatementExecutor statementExecutor = ((BudoRedisJdbcConnection) preparedStatement.getConnection()).getStatementExecutor();
        Object eval = statementExecutor.eval(script);

        Object[] valueArray;
        if (eval instanceof List) {
            List list = (List) eval;
            valueArray = list.toArray(new Object[list.size()]);
        } else {
            valueArray = new Object[] { eval };
        }

        ResultSet resultSet = new ObjectArrayResultSet(new String[] { "eval" }, valueArray);
        ((BudoRedisJdbcPreparedStatement) preparedStatement).setResultSet(resultSet);
    }
}